---
layout: layouts/page.njk
title: Slider
description: An input where the user selects a value from within a given range.
toc:
  - label: Usage
    id: usage
---

{% from "macros/code_preview.njk" import code_preview %}
{% from "macros/code_block.njk" import code_block %}

{% set code %}<input
  type="range"
  class="input w-full"
  min="0"
  max="100"
  value="50"
>
<script>
  (() => {
    const sliders = document.querySelectorAll('input[type="range"].input');
    if (!sliders) return;

    const updateSlider = (el) => {
      const min = parseFloat(el.min || 0);
      const max = parseFloat(el.max || 100);
      const value = parseFloat(el.value);
      const percent = (max === min) ? 0 : ((value - min) / (max - min)) * 100;
      el.style.setProperty('--slider-value', `${percent}%`);
    };

    sliders.forEach(slider => {
      updateSlider(slider);
      slider.addEventListener('input', (event) => updateSlider(event.target));
    });
  })();
</script>{% endset %}
{{ code_preview("slider", code, "w-full max-w-sm") }}

<h2 id="usage"><a href="#usage">Usage</a></h2>

<section class="prose">
  <p>You can style an <code>&lt;input type="range"&gt;</code> element by either adding the <code>input</code> class or having a parent with the <code>form</code> class (<a href="/components/form">read more about form</a>). However, the range input also requries some Javacript code to be able to paint the left side of the slider.</p>
</section>

{{ code_block(code) }}